(function($) {
	$.extend({
		parsePage : function(options) {
			var defaults = {};
			var page = {};
            var title = $("head title").text();
            
			if ($("head meta[name=keywords]").length > 0) {
				var keywords = $("head meta[name=keywords]").attr("content")
						.split(/\s+|,/);

				function sortByLength(a, b) {
					return a.length > b.length;
				}

				keywords = keywords.sort(sortByLength);
                console.debug(keywords);

				var MAX_TAGS = 5;
				page.keywords = "";
				for ( var i = 0; i < MAX_TAGS && i < keywords.length; i++) {
					page.keywords += keywords[i] + ",";
				}
			}
			if ($("head meta[name=description]").length > 0) {
				page.description = $("head meta[name=description]").attr(
						"content");
			}
			page.domain = window.location.pathname;

			var root = {
				children : [],
				text : ""
			};

			var parser = {
				parse : function(parent, dom) {
					var tagName = $(dom).prop("tagName");

					if (tagName == undefined || tagName == "IFRAME"
							|| tagName == "SCRIPT" || tagName == "STYLE"
							|| tagName == "FRAME") {
						return;
					}

					var node = {
						dom : dom,
						text : "",
						tagName : tagName,
						children : []
					};

					parent.children.push(node);

					$(dom).contents().each(function() {
						if (this.nodeType == 3) {
							var text = $.trim($(this).text());

							if (text.length > 0) {
								node.text += text + " ";
								parent.text += text + " ";
							}
						} else {
							parser.parse(node, this);
						}
					});
				}
			};

			parser.parse(root, $("body"));

			console.debug(root);

			var booster = {
				root : root,
				factor : 0,
				candidate : {},
				getContentNode : function() {
					this.getContentNode0(root);
					return this.candidate;
				},
				getContentNode0 : function(node) {
					var factor = node.text.length;
					if (factor > booster.factor) {
						booster.candidate = node;
						booster.factor = factor;
					}

					for ( var i = 0; i < node.children.length; i++) {
						this.getContentNode0(node.children[i]);
					}
				}
			};

			var node = booster.getContentNode();
			console.debug(node);

			page.content = node.text;

			return page;
		}
	});
})(jQuery);

chrome.extension.connect().postMessage($.parsePage());
